//
//  MyIncomeViewController.swift
//  globalcarbusiness
//
//  Created by dongzhenyu on 2017/8/21.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit
import SwiftyJSON

class MyIncomeViewController: UIViewController {

    fileprivate var dayChart: ChartHelper!
    fileprivate var monthChart: ChartHelper!
    fileprivate var yearChart: ChartHelper!
    
    fileprivate var dayCountLabel: UILabel!
    fileprivate var monthCountLabel: UILabel!
    fileprivate var yearCountLabel: UILabel!
    
    fileprivate var dayBtn: UIButton!
    fileprivate var monthBtn: UIButton!
    fileprivate var yearBtn: UIButton!
    
    fileprivate var datePickerView: DatePickerView!
    fileprivate var seg: HMSegmentedControl!
    
    fileprivate lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: 40*HEIGHT_SCALE, width: kScreenW, height: kScreenH - 64))
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.contentSize = CGSize(width: kScreenW * 3, height: kScreenH - 64 - 40*HEIGHT_SCALE)
        scrollView.delegate = self
        scrollView.bounces = false
        scrollView.backgroundColor = UIColor.colorWithHexString("f8f8f8")
        return scrollView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = RGBA(248, g: 248, b: 248, a: 1)
        
        setupNav()
        
        setupSegment()
        
        setupHeader()
        
        setupChart()
        
        loadData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.barStyle = .black
    }
}

// MARK: - data
extension MyIncomeViewController {
    fileprivate func loadData() {
        loadDataWithFormat(timeformat:"%y-%m-%d")
        loadDataWithFormat(timeformat:"%y-%m")
        loadDataWithFormat(timeformat:"%y")
    }
    
    fileprivate func loadDataWithFormat(timeformat: String) {
        showLoading()
        let url = Base_url + CASH_OUT_DETAIL
        var time: String
        if timeformat == "%y-%m-%d" {
            time = dayBtn.title(for: .normal)!
        } else if timeformat == "%y-%m" {
            time = monthBtn.title(for: .normal)! + "-00"
        } else if timeformat == "%y" {
            time = yearBtn.title(for: .normal)! + "-00-00"
        } else {
            fatalError("时间格式不对!")
        }
        
        NetworkTools.shareInstance.requestData(url, .get, ["time": time, "format": timeformat]) { (result, isSuccess) in
//            DZYLog(result)
            if isSuccess == true {
                self.hideLoading()
                let json = JSON(result)
                var sum: Float = 0
                let array = json["detail"].arrayValue
                
                var baoyang: NSNumber = 0
                var meirong: NSNumber = 0
                var xiche: NSNumber = 0
                var shanfu: NSNumber = 0
                var banpen: NSNumber = 0
                var peijian: NSNumber = 0
                var daodian4s: NSNumber = 0
                
                
                array.map({ (item) in
                    switch item["name"].stringValue {
                    case "到店保养":
                        baoyang = item["sum"].numberValue
                    case "美容":
                        meirong = item["sum"].numberValue
                    case "洗车":
                        xiche = item["sum"].numberValue
                    case "闪付":
                        shanfu = item["sum"].numberValue
                    case "钣喷":
                        banpen = item["sum"].numberValue
                    case "配件":
                        peijian = item["sum"].numberValue
                    case "到店保养4s":
                        daodian4s = item["sum"].numberValue
                    default:
                        fatalError("数据格式错误")
                    }
                    
                    sum += abs(item["sum"].floatValue)
                })
                
                let data = [baoyang, meirong, xiche, shanfu, daodian4s, banpen, peijian]
                
                switch timeformat {
                    case "%y-%m-%d":
                        self.dayCountLabel.text = String(format: "%.2f", sum)
                        self.dayChart.updateData(data)
                    case "%y-%m":
                        self.monthCountLabel.text = String(format: "%.2f", sum)
                        self.monthChart.updateData(data)
                    case "%y":
                        self.yearCountLabel.text = String(format: "%.2f", sum)
                        self.yearChart.updateData(data)
                    default:
                        break
                }
                
            } else {
                self.hideLoading()
                self.showHUD(.failure, text: "连接失败")
            }
        }
    }
}

// MARK: - init code
extension MyIncomeViewController {
    
    fileprivate func setupNav() {
        title = "收入明细"
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: RGBA(34, g: 34, b: 34, a: 1)]
        navigationController?.navigationBar.barStyle = .default
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "icon_fanhui", target: self, action: #selector(leftItemClick))
        
    }
    
    fileprivate func setupSegment() {
        let titles = ["日报", "月报", "年报"]
        let segment = HMSegmentedControl(sectionTitles: titles)
        self.seg = segment
        segment?.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 40*HEIGHT_SCALE)
        view.addSubview(segment!)
        
        segment?.selectedSegmentIndex = 0
        segment?.isVerticalDividerEnabled = true
        segment?.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed
        segment?.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown
        segment?.backgroundColor = UIColor.colorWithHexString("ffffff")
        segment?.borderType = .bottom
        segment?.borderColor = UIColor.colorWithHexString("dddddd")
        segment?.borderWidth = 0.5
        segment?.selectionIndicatorColor = UIColor.colorWithHexString("70beff")
        segment?.selectionIndicatorHeight = 2
        segment?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.colorWithHexString("222222"), NSFontAttributeName: UIFont.systemFont(ofSize: 14*WIDTH_SCALE)]
        segment?.selectedTitleTextAttributes = [NSForegroundColorAttributeName: UIColor.colorWithHexString("70beff"), NSFontAttributeName: UIFont.systemFont(ofSize: 16*WIDTH_SCALE)]

        view.addSubview(scrollView)
        scrollView.scrollRectToVisible(CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - 64 + 141*HEIGHT_SCALE), animated: true)
        scrollView.setContentOffset(CGPoint(x: 0,y: 0), animated: false)
        
        self.seg.indexChangeBlock = { (index: NSInteger) in
            self.scrollView.scrollRectToVisible(CGRect(x: kScreenW * CGFloat(index), y: 0, width: kScreenW, height: kScreenH - 64 - 141*HEIGHT_SCALE), animated: true)
            switch index {
            case 0:
                self.dayChart.barChart.stroke()
            case 1:
                self.monthChart.barChart.stroke()
            case 2:
                self.yearChart.barChart.stroke()
            default:
                break
            }
        }
    }
    
    fileprivate func setupHeader() {
        
        for i in 0...2 {
            let label = UILabel()
            label.text = "总计(元)"
            label.textColor = UIColor.colorWithHexString("444444")
            label.font = UIFont.systemFont(ofSize: 14*WIDTH_SCALE)
            scrollView.addSubview(label)
            label.snp.makeConstraints({ (make) in
                make.left.equalTo(scrollView).offset(kScreenW*CGFloat(i) + 12*WIDTH_SCALE)
                make.top.equalTo(scrollView)
                make.height.equalTo(50*HEIGHT_SCALE)
            })
            
            let countLabel = UILabel()
            countLabel.text = ""
            countLabel.tag = 100+i
            countLabel.textColor = UIColor.colorWithHexString("70beff")
            scrollView.addSubview(countLabel)
            countLabel.snp.makeConstraints({ (make) in
                make.left.equalTo(label.snp.right).offset(10*WIDTH_SCALE)
                make.top.equalTo(scrollView)
                make.height.equalTo(50*HEIGHT_SCALE)
            })
            
            if i == 0 {
                dayCountLabel = countLabel
            } else if i == 1 {
                monthCountLabel = countLabel
            } else if i == 2 {
                yearCountLabel = countLabel
            }
            
            let btn = UIButton(type: .custom)
            btn.setTitleColor(UIColor.colorWithHexString("888888"), for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 14*WIDTH_SCALE)
            btn.frame = CGRect(x: kScreenW - 120*WIDTH_SCALE + kScreenW*CGFloat(i), y: 0, width: 100*WIDTH_SCALE, height: 50*HEIGHT_SCALE)
            scrollView.addSubview(btn)
            btn.tag = 1000+i
            let date = Date()
            let formatter = DateFormatter()
            switch i {
            case 0:
                formatter.dateFormat = "yyyy-MM-dd"
                dayBtn = btn
            case 1:
                formatter.dateFormat = "yyyy-MM"
                monthBtn = btn
            case 2:
                formatter.dateFormat = "yyyy"
                yearBtn = btn
            default:
                break
            }
            
            btn.setTitle(formatter.string(from: date), for: .normal)
            btn.addTarget(self, action: #selector(dateBtnClick(sender:)), for: .touchUpInside)
            
        }
    }
    
    fileprivate func setupChart() {
        for i in 0...2 {
            let helper = ChartHelper(frame: CGRect(x: CGFloat(i)*kScreenW, y: 50*HEIGHT_SCALE, width: kScreenW, height: 270*HEIGHT_SCALE), type: 1)
            scrollView.addSubview((helper?.barChart)!)
            switch i {
            case 0:
                dayChart = helper
            case 1:
                monthChart = helper
            case 2:
                yearChart = helper
            default:
                break
            }
        }
    }
}

// MARK: - event
extension MyIncomeViewController {
    
    @objc fileprivate func leftItemClick() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc fileprivate func dateBtnClick(sender: UIButton) {
        let pickerView = DatePickerView()
        self.datePickerView = pickerView
        
        switch sender.tag - 1000 {
        case 0:
            pickerView.showSelector(formatter: DatePickerView.SelectorFormatter.Day)
        case 1:
            pickerView.showSelector(formatter: DatePickerView.SelectorFormatter.Month)
        case 2:
            pickerView.showSelector(formatter: DatePickerView.SelectorFormatter.Year)
        default:
            break
        }
        
        pickerView.handleDateStr = { (dateStr) in
            sender.setTitle(dateStr, for: .normal)
            
            switch sender.tag - 1000 {
            case 0:
                self.loadDataWithFormat(timeformat: "%y-%m-%d")
            case 1:
                self.loadDataWithFormat(timeformat: "%y-%m")
            case 2:
                self.loadDataWithFormat(timeformat: "%y")
            default:
                break
            }
        }
    }
}

extension MyIncomeViewController: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageW = scrollView.width
        let currentPage: UInt = UInt(scrollView.contentOffset.x/pageW)
        self.seg.setSelectedSegmentIndex(currentPage, animated: true)
        
    }
}

